<?php

/**
 * This is the model class for table "{{count_referer}}".
 *
 * The followings are the available columns in table '{{count_referer}}':
 * @property integer $CountID
 * @property string $Domain
 * @property string $DootDomain
 * @property integer $Year
 * @property integer $Month
 * @property integer $Day
 * @property integer $Number
 * @property integer $AddTime
 */
class CountRefererModel extends BaseModel
{
    public static $db;
    public function getDbConnection(){
        if(self::$db!==null){
            return self::$db;
        }else{
            self::$db=Yii::app()->getComponent('db_count');
            if(self::$db instanceof CDbConnection)
                return self::$db;
            else
                throw new CDbException('连接出错');                    
        }            
    }
    //数据保存前置操作
    protected function beforeSave() {
        if ($this->isNewRecord) {
            $this->AddTime = TIME_TIME;
        }
        return true;
    }
    //执行分析
    public function sendFenxi($intStartTime = '', $intEndTime = '') {
        set_time_limit(400);
        if (empty($intStartTime)) {
            $intStartTime = strtotime(date('Y-m-d 00:00:00'));
        }
        if (empty($intEndTime)) {
            $intEndTime = strtotime(date('Y-m-d 23:59:59'));
        }

        //总共需要统计多少天的量
        $intCount = ($intEndTime - $intStartTime)%86400;
        for($i = 0; $i < $intCount; $i++){
            self::saveDataOneDate($intStartTime + $i*86400);
        }

    }

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{count_referer}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('Domain, DootDomain', 'required'),
			array('Year, Month, Day, Number, AddTime', 'numerical', 'integerOnly'=>true),
			array('Domain, DootDomain', 'length', 'max'=>255),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('RecordTime, Domain, DootDomain, Year, Month, Day, Number, AddTime', 'safe'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'CountID' => '主键ID',
			'Domain' => '域名',
			'DootDomain' => '根域名',
			'Year' => '年',
			'Month' => '月',
			'Day' => '日',
			'Number' => '数量',
			'AddTime' => '添加时间',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('CountID',$this->CountID);
		$criteria->compare('Domain',$this->Domain,true);
		$criteria->compare('DootDomain',$this->DootDomain,true);
		$criteria->compare('Year',$this->Year);
		$criteria->compare('Month',$this->Month);
		$criteria->compare('Day',$this->Day);
		$criteria->compare('Number',$this->Number);
		$criteria->compare('AddTime',$this->AddTime);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	public function createSearchCriteria()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

        if (isset($_GET['start_time']) && $_GET['start_time']) {
            $start_time = strtotime($_GET['start_time']);
            $criteria->addCondition("AddTime >= {$start_time}");
        }
        if (!empty($_GET['end_time'])) {
            $end_time = strtotime($_GET['end_time']) + 86399;
            $criteria->addCondition("AddTime < {$end_time}");
        }     


		$criteria->compare('CountID',$this->CountID);
		$criteria->compare('Domain',$this->Domain,true);
		$criteria->compare('DootDomain',$this->DootDomain,true);
		$criteria->compare('Year',$this->Year);
		$criteria->compare('Month',$this->Month);
		$criteria->compare('Day',$this->Day);
		$criteria->compare('Number',$this->Number);
		$criteria->compare('AddTime',$this->AddTime);

		return $criteria;
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return CountRefererModel the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

    /**
     * 通过一个时间戳或者时间然后判断是分析哪张表的数据，然后执行分析
     * @return [type] [description]
     */
    public static function saveDataOneDate($mixTime){
        if(is_numeric($mixTime)){
            //时间戳格式
        }else{
            //时间格式
            $mixTime = strtotime($mixTime);
        }
        $strTime = date('Ymd', $mixTime);
        $intYear = date('Y', $mixTime);
        $intMonth = date('m', $mixTime);
        $intDay = date('d', $mixTime);
        //设置分析哪张GuestDataModel表。。。
        GuestDataModel::$strTableName = '{{guest_data'.$strTime.'}}';

        $objModel = new GuestDataModel();
        $objCriteria = new CDbCriteria(array(
            'condition' => 'Referer != "" AND Year = '.$intYear.' AND Month = '.$intMonth.' AND Day = ' . $intDay,
            'group' => 'RefererDomain,RefererRootDomain',
            'select' => 'RefererRootDomain,RefererDomain,count(*) ModuleID',//这里可以用某一个本来就存在的字段来代替你的这个count(*)
        ));
        $objDatas = $objModel->findAll($objCriteria);

        foreach($objDatas as $objData){
            $arrData = array(
                'Domain' => $objData->RefererDomain,
                'DootDomain' => $objData->RefererRootDomain,
                'Year' => $intYear,
                'Month' => $intMonth,
                'Day' => $intDay,
                //'RecordTime' => strtotime($intYear.'-'.$intMonth.'-'.$intDay),
            );
            $objReferer = self::model()->find(BaseModel::getC($arrData));
            if($objReferer){
                $objReferer->Number = $objData->ModuleID;
            }else{
                $objReferer = new CountRefererModel();
                $objReferer->attributes = $arrData;
                $objReferer->Number = $objData->ModuleID;
                $objReferer->save(false);
            }
            echo "域名：{$arrData['Domain']},{$intMonth}月{$intDay}日分析完成</br>";
        }

        return true;         
    }


}
